package com.haiyou.mini.programs.strategy;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.HashMap;
import java.util.Map;

/**
 * ContextStrategy
 * 客户端
 * 策略核心功能,获取所有策略注解的类型
 * 并将对应的class初始化到ContextStrategy中
 **/
@Slf4j
public class WxPayContextStrategy implements ApplicationContextAware {

    @Autowired
    private ApplicationContext applicationContext;

    /**
     * 存放所有策略类Bean的map
     */
    private static Map<String, Class<WxMiniPayStrategy>> strategyBeanMap = new HashMap<>();

    private WxMiniPayStrategy getStrategy(String type) {
        Class<WxMiniPayStrategy> strategyClass = strategyBeanMap.get(type);
        if (strategyClass == null) {
            log.error("---->没有对应的策略类型：{}，strategyBeanMap={}", type, strategyBeanMap);
            throw new RuntimeException("没有对应的类型");
        }
        //从容器中获取对应的策略Bean
        return applicationContext.getBean(strategyClass);
    }

    public void executeStrategy(Map<String, String> notifyMap) {
        getStrategy(notifyMap.get("attach")).payHandler(notifyMap);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        //获取所有策略注解的Bean
        Map<String, Object> strategyMap = applicationContext.getBeansWithAnnotation(WxPayType.class);
        log.info("-------->strategyMap={}", strategyMap);
        strategyMap.forEach((k, v) -> {
            Class<WxMiniPayStrategy> strategyClass = (Class<WxMiniPayStrategy>) v.getClass();
            String type = strategyClass.getAnnotation(WxPayType.class).attach();
            //将class加入map中,type作为key
            strategyBeanMap.put(type, strategyClass);
        });
    }
}